package com.tfj.mvp.tfj.msg;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.tfj.DemoHelperChat;
import com.hyphenate.tfj.R;
import com.hyphenate.tfj.ui.ChatActivity;
import com.tfj.comm.activity.HomePageActivity;
import com.tfj.comm.service.EmService;
import com.tfj.mvp.base.BaseFragment;
import com.tfj.mvp.tfj.msg.bean.ItemMessage;
import com.tfj.widget.sliding.SlideRecyclerView;
import com.tfj.widget.sliding.SlidingAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by HuangQiang on 2017/12/21.
 *
 * @author HuangQiang
 * @github https://github.com/HuangQiang
 */
@SuppressLint("ValidFragment")
public class VMsgFragment extends BaseFragment<PMsgImpl> implements CMsg.IVMsg, OnTabSelectListener {
    @BindView(R.id.recyclerView_message)
    SlideRecyclerView recyclerViewMessage;
    Unbinder unbinder;
    private String userId = "";
    private List<ItemMessage> itemMessages_person = new ArrayList<ItemMessage>();
    private SlidingAdapter slidingAdapter;
    private String title = "";
    public static VMsgFragment newInstance(String title) {
        VMsgFragment fragment = new VMsgFragment(title);
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }
    @SuppressLint("ValidFragment")
    public VMsgFragment(String title) {
        this.title = title;
    }

    public VMsgFragment() {
    }

    @Override
    public void onResume() {
        super.onResume();
        getConversation();
    }

    @Override
    protected void initView() {
        recyclerViewMessage.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

    }
    //将获取的回话记录转成自己想要的数据
    public void getConversation() {
        int countAll = 0;
        int countTop = 0;
        String lastMessage = "";
        List<ItemMessage> itemMessages_Person = new ArrayList<ItemMessage>();
        itemMessages_person = new ArrayList<ItemMessage>();
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        Log.i(TAG, "conversations--->" + JSONObject.toJSONString(conversations));
        Iterator iter = conversations.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, EMConversation> entry = (Map.Entry<String, EMConversation>) iter.next();
            EMConversation emConversation = entry.getValue();
            EMMessage emMessage_last = emConversation.getLastMessage();
            Log.i(TAG, "最新的一条聊天记录-->" + JSONObject.toJSONString(emMessage_last));
            Log.i(TAG, "最新的一条的扩展信息-->" + JSONObject.toJSONString(emMessage_last.ext()));
            JSONObject jsonObject_latest = JSONObject.parseObject(JSONObject.toJSONString(emMessage_last));
            String userInfo_from = "";
            String userInfo_to = "";
            JSONObject jsonObjectFrom = null;
            JSONObject jsonObjectTo = null;
            JSONObject jsonObjectShopFrom = null;
            ItemMessage itemMessage = new ItemMessage();
            String unreadMsgCount = emConversation.getUnreadMsgCount() + "";
            String type = jsonObject_latest.getString("chatType");
//            //最新的一条  获取最新的一条的时间 内容 id
            String messageContent = jsonObject_latest.getJSONObject("body").getString("message");
            String fromUserId = jsonObject_latest.getString("from");
            String toUserId = jsonObject_latest.getString("to");
            String msgTime = jsonObject_latest.getString("msgTime");
            String msgId = jsonObject_latest.getString("msgId");
            String contentType = jsonObject_latest.getString("type");
            String avatar = "";
            String username = "";
            Log.i(TAG, "userId--->" + userId);
            if (fromUserId.equals(userId)) {
                //说明最后一条是自己发给的自己
                if (jsonObjectTo != null) {
                    avatar = jsonObjectTo.getString("avatar");
                    username = jsonObjectTo.getString("name");
                    fromUserId = jsonObjectTo.getString("phone");
                    itemMessage.setFromUserName(username);

                }
            } else {
                if (jsonObjectFrom != null) {
                    avatar = jsonObjectFrom.getString("avatar");
                    username = jsonObjectFrom.getString("name");
                    itemMessage.setFromUserName(username);
                }
            }
            itemMessage.setContentType(contentType);
            itemMessage.setFromUserId(fromUserId);
            itemMessage.setToUserId(toUserId);
            itemMessage.setAvatar(avatar);
            itemMessage.setMsgId(msgId);
            itemMessage.setMsgTime(msgTime);
            itemMessage.setType(type);
            itemMessage.setUnreadMsgCount(unreadMsgCount);
            itemMessage.setMessageContent(messageContent);
            //切换到商户状态
            //不是商户消息(带商户的消息全部过滤)
            if (jsonObjectShopFrom == null) {
                if (type.equals("Chat")) {
                    //个人聊天
                    itemMessage.setUserFromJson(userInfo_from);
                    itemMessage.setUserToJson(userInfo_to);
                    itemMessages_Person.add(itemMessage);
                }
            }
            //商户消息
            else {
                countTop = countTop + Integer.parseInt(unreadMsgCount);
                String shopNameMessage = jsonObjectShopFrom.getString("shopName");
                lastMessage = shopNameMessage + ":" + messageContent;
            }
            countAll = countAll + Integer.parseInt(unreadMsgCount);
        }
        Collections.sort(itemMessages_Person, new Comparator<ItemMessage>() {
            public int compare(ItemMessage o1, ItemMessage o2) {
                if (Long.parseLong(o1.getMsgTime()) < Long.parseLong(o2.getMsgTime())) {
                    return 1;
                } else {
                    return -1;
                }

            }
        });
        Log.i(TAG, "itemMessages_Person--->" + JSONObject.toJSONString(itemMessages_Person));
        itemMessages_person.addAll(itemMessages_Person);
        //设置消息个数
        HomePageActivity.refreshUnReadCount(countAll);
        renderChatListPerson();
    }

    public void renderChatListPerson() {
        slidingAdapter = new SlidingAdapter(getActivity(), itemMessages_person);
        recyclerViewMessage.setAdapter(slidingAdapter);
        //删除聊天
        slidingAdapter.setOnDeleteClickListener(new SlidingAdapter.OnDeleteClickLister() {
            @Override
            public void onDeleteClick(View view, int position) {
                    showToast("删除成功");
                    //删除和某个user会话，如果需要保留聊天记录，传false
                    EMClient.getInstance().chatManager().deleteConversation(itemMessages_person.get(position).getFromUserId(), true);
                    slidingAdapter.getDataAll().remove(position);
                    slidingAdapter.notifyDataSetChanged();
                    recyclerViewMessage.closeMenu();
            }
        });
        slidingAdapter.setOnOutClickListener(new SlidingAdapter.OnOutClickClickLister() {
            @Override
            public void onOutClickClick(View view, int position) {
                String otherId = "";
                String userIdTo =   slidingAdapter.getData(position).getToUserId();
                String userIdFrom =   slidingAdapter.getData(position).getFromUserId();
                String currentName =  DemoHelperChat.getInstance().getCurrentUsernName();
                if(currentName.equals(userIdFrom)){
                    //自己发的
                    otherId  =  userIdTo;
                }else{
                    otherId = userIdFrom;
                }
                startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", otherId));
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(EmService.EM_ACTION);
        getActivity().registerReceiver(imReceiver, filter);
    }

    private BroadcastReceiver imReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (EmService.EM_ACTION.equals(action)) {
                Log.i(TAG, "消息界面监听到的消息为--->" + intent.getStringExtra("message"));
                getConversation();
            }
        }
    };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.fragment_msg;
    }

    @Override
    public void createPresenter() {
        mPresenter = new PMsgImpl(mContext, this);
    }

    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(imReceiver);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onTabSelect(int position) {
        showToast("position-->"+position);
    }

    @Override
    public void onTabReselect(int position) {

    }
}
